//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Microsoft.Research.DataLayer
{
    internal partial class ConnectionManagerDialog_SQL : Microsoft.Research.DataLayer.ConnectionManagerDialog_Base
    {
        public ConnectionManagerDialog_SQL()
        {
            InitializeComponent();

            Presets.OnLoadPreset += new ConnMgrDlg_Presets.PresetHandler(presets_OnLoadPreset);
        }

        public override string DisplayStatus
        {
            get
            {
                return string.Format("Server: {0}, Database: {1}", this.serverName.Text,
                    this.database.Text);
            }
        }

        private void presets_OnLoadPreset(IConnMgrInfoParams inPreset)
        {
            SQLConnectionParameters preset = (SQLConnectionParameters)inPreset;

            if (preset != null)
            {
                string serverName;
                bool trustedConn;
                bool userPass;
                string username;
                string password;
                bool encrypted;
                string database;

                preset.Load(out serverName, out trustedConn, out userPass, out username, out password,
                    out encrypted, out database);

                this.serverName.Text = serverName;
                this.trustedConn.Checked = trustedConn;
                this.userPass.Checked = userPass;
                this.username.Text = username;
                this.password.Text = password;
                this.encrypt.EncryptPassword.Checked = encrypted;
                this.database.Text = database;
            }
            else
            {
                this.serverName.Text = "";
                this.trustedConn.Checked = false;
                this.userPass.Checked = false;
                this.username.Text = "";
                this.password.Text = "";
                this.encrypt.EncryptPassword.Checked = false;
                this.database.Text = "";
            }

            FireOnPropertyChange(false);
        }

        private void savePreset_Click(object sender, EventArgs e)
        {
            SaveItem();
        }

        protected override void SaveItem()
        {
            SQLConnectionParameters preset = (SQLConnectionParameters)Presets.CurrentPreset;
            preset.Update(preset.Name, this.serverName.Text, this.trustedConn.Checked,
                this.username.Text, this.password.Text, this.database.Text, this.encrypt.EncryptPassword.Checked);
            base.SaveItem();
        }

        private void serverName_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void serverName_TextChanged(object sender, EventArgs e)
        {
            FireOnPropertyChange(true);
        }

        private Connection CreateConnection(string altDatabase)
        {
            Connection testConn;

            if (this.trustedConn.Checked)
            {
                testConn = SQLConnection.CreateTrusted(
                    this.serverName.Text,
                    altDatabase ?? this.database.Text);
            }
            else
            {
                testConn = SQLConnection.CreateUserPass(
                    this.serverName.Text,
                    this.username.Text,
                    this.password.Text,
                    altDatabase ?? this.database.Text);
            }

            return testConn;
        }

        /// <summary>
        /// Tests connection and give user feedback
        /// </summary>
        public override void TestConnection()
        {
            Connection testConn = CreateConnection(null);
            TestConnection(testConn);
        }

        public override Connection Connection
        {
            get
            {
                return CreateConnection(null);
            }
        }

        private void trustedConn_CheckedChanged(object sender, EventArgs e)
        {
            FireOnPropertyChange(true);
        }

        private void encrypt_OnEncryptionChecked(object sender, EventArgs e)
        {
            FireOnPropertyChange(true);
        }

        private void database_DropDown(object sender, EventArgs e)
        {
            try
            {
                string currentDb = database.Text;

                Cursor = Cursors.WaitCursor;

                Connection listConn = CreateConnection("master");
                listConn.Open();

                ISQLManagementServices mgmtSvc = (ISQLManagementServices)listConn;

                string userToQuery;

                if (this.trustedConn.Checked)
                    userToQuery = string.Format("{0}\\{1}",
                        System.Environment.UserDomainName, System.Environment.UserName);
                else
                    userToQuery = this.username.Text;

                string[] dbList = mgmtSvc.GetDatabaseList(userToQuery);

                database.Items.Clear();
                database.Items.AddRange(dbList);
            }
            catch (Exception)
            {
                MessageBox.Show("Cannot retrieve the list of databases from server", "ERROR",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// Creates a new preset from the user input
        /// </summary>
        /// <param name="name"></param>
        /// <param name="newPreset"></param>
        /// <param name="provider"></param>
        protected override void CreateNewPreset(string name, out IConnMgrInfoParams newPreset, out ProviderPkgInfo provider)
        {
            if (trustedConn.Checked)
                newPreset = SQLConnectionParameters.CreateTrustedConnection(name, serverName.Text, database.Text);
            else
                newPreset = SQLConnectionParameters.CreateUserPassConnection(name, username.Text, password.Text, serverName.Text, database.Text);

            provider = this.Provider;
        }

        public override bool CanTestConnection()
        {
            return (trustedConn.Checked ?
                (serverName.Text.Length > 0 && database.Text.Length > 0) :
                (serverName.Text.Length > 0 && database.Text.Length > 0 && username.Text.Length > 0));
        }
    }
}
